<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2018/3/22
 * Time: 9:19
 */

namespace app\api\model;
use app\common\lib\exception\ApiException;
use think\Model;
use think\Log;
use think\Db;
use app\api\model\Student as StudentModel;
use app\api\model\Account as AccountModel;
use app\admin\model\Coin;

class Donation extends Model
{


    /**
     * 捐书领取学币
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getCoinByDonation(){
        if (empty($_POST)) {
            throw new ApiException('数据不合法',404);
        }
        // id int donation表id 必传
        if (empty($_POST['id'])) {
            throw new ApiException('id is not find', 404);
        }
        // donation_id int 捐赠人id 必传
        if (empty($_POST['donation_id'])) {
            throw new ApiException('donation_id is not find', 404);
        }

        Db::startTrans();

        try {
            $id =$_POST['id'];
            $donation_id = $_POST['donation_id'];
            $info =Db::name('donation')->where(array('id'=>$id,'donation_id'=>$donation_id))->find();

            if($info['is_receive']==0){

                $donation=$this::get($id);
                $donation->is_receive = 1;
                $res = $donation->save();

                if($res){
                    $student = StudentModel::get(['student_id' => $donation_id]);
                    $student->coin = $student->coin + $info['get_coin'];
                    $get_coin = $student->save();
                    if($get_coin){

                        $coin['user_id'] =$donation_id;
                        $coin['account_sn'] =date("YmdHis").rand(1000,9999);
                        $coin['cost_description']='领取捐书学币';
                        $coin['cost']=$info['get_coin'];
                        $coin['record_time']=time();
                        $coin['cost_type'] = 1;
                        $coin['channel'] = 'backstage  ';
                        $coin['status'] =  1;

                        $ret = (new Account())->insertGetId($coin);

                        if($ret){
                            Db::commit();
                            return show(config('code.success'),'领取成功',$info);
                        }else{
                            Db::name('account')->where('id',$ret)->setField('status', '0');
                            return show(config('code.error'),'流水记录失败！');
                        }
                    }else{
                        return show(config('code.error'),'student表更新失败！');
                    }
                }else{
                    return show(config('code.error'),'donation状态修改失败！');
                }
            }else{
                return show(config('code.error'),'已领取，不可重复领取！');
            }
        } catch (\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),500);
        }
    }

    /**
     * @查询本人的捐赠记录或者募捐记录
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function getDonationHistory($data){
        $where = [];
        /* status int 捐赠状态 状态 1 查询本人捐赠记录
                                  2 查询本人的募捐记录
                                  3 查询本人尚未领取学币的捐书记录
        */
        if (!empty($data['status'])) {
            if ($data['status'] == 1) {
                $where = array('donation_id' => $data['donation_id']);
            } elseif ($data['status'] == 2) {
                $where = array('donation_collect_id' => $data['donation_id']);
            }elseif($data['status'] == 3){
                $where = array('donation_id'=>$data['donation_id'],"is_receive"=>0);
            }
        }
        $info = Db::name('donation')
            ->alias("donation")
            ->join('user', 'donation_id=user.id', 'LEFT')
            ->field('donation.*,user.tel,user.full_name')
            ->order('donation.id desc')
            ->where($where)
            ->select();
        return $info;
    }
    /**
     * @查询本人的捐赠记录或者募捐记录
     * @donation_id 捐赠人id int 必传
     * @status int 状态条件必传 1查询本人的捐赠记录 2查询本人的募捐记录 3查询没有领取学币的。
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function index(){
        if (empty($_GET)) {
            throw new ApiException('数据不合法',404);
        }
        // donation_id int 捐赠人id 必传
        if (empty($_GET['donation_id'])) {
            throw new ApiException('donation_id is not found',404);
        }
        if (empty($_GET['status'])) {
            throw new ApiException('status is not found',404);
        }
        try {
            $info = $this->getDonationHistory($_GET);

            return show(config('code.success'), '获取数据成功', $info);

        } catch (\Exception $e) {
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 募捐人查询某人捐赠记录
     * @author 巫玉梅 <1120504614@qq.com>
     * @return array|string|\think\response\Json
     */
    public function donorGetSbDonationBook(){ //donor 募捐人
        if (empty($_POST)) {
            throw new ApiException('数据不合法',404);
        }
        // tel int 捐赠人电话 必传
        if (empty($_POST['tel'])) {
            throw new ApiException('tel is not found',404);
        }
        // tel int 募捐人id 必传
        if (empty($_POST['id'])) {
            throw new ApiException('id is not found',404);
        }

        try{
           // dump($_POST);die;
            $donation = Db::name('donation')
                ->alias("donation")
                ->join('user','donation_id=user.id ','LEFT')
                ->where('user.tel ="'.$_POST['tel'].'" AND donation.donation_collect_id="'.$_POST['id'].'"')
                ->field('user.tel,user.full_name,donation_price,get_coin,donation_time,donation_book,submit_status')
                ->order('donation.id desc')
                ->select();

            return show(config('code.success'), '获取数据成功', $donation);

        }catch(\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 捐赠信息查重
     * @param donation_tel string 捐赠电话 *必填
     * @param donation_book string 捐赠书籍 *必填
     * @param donation_name string 捐赠姓名 *必填
     * @param donation_price int 捐赠价格 *必填
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function selectDonation(){ //donation/is_donation
        $data = $_POST;
        if(empty($data)) {
            throw new ApiException('数据不合法', 404);
        }

        if(!isset($data['donation_tel'])){
            throw new ApiException('donation_tel is not found',404);
        }

        if(!isset($data['donation_book'])){
            throw new ApiException('donation_book is not found',404);
        }

        if(!isset($data['donation_name'])){
            throw new ApiException('donation_name is not found',404);
        }



        try{
            $info = Db::name('donation')
                ->alias('d')
                ->join('user ','d.donation_id=user.id','LEFT')
                ->where('tel='.$data['donation_tel'].' AND donation_book="'.$data['donation_book'].'" AND full_name="'.$data['donation_name'].'"')
                ->find();

            return show(config('code.success'), '',$info);

        }catch (\Exception $e){
            Log::write($e->getMessage());
            throw new ApiException($e->getMessage(),400);
        }
    }

    /**
     * 添加捐赠信息
     * @param donation_tel string 捐赠电话 *必填
     * @param donation_book string 捐赠书籍 *必填
     * @param donation_name string 捐赠姓名 *必填
     * @param donation_price int 捐赠价格 *必填
     * @param donation_collect_id int 募捐人user_id *必填
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function addDonation(){
        $data = $_POST;
        if(empty($data)) {
            throw new ApiException('数据不合法', 404);
        }

        if(!isset($data['donation_tel'])){
            throw new ApiException('donation_tel is not found',404);
        }

        if(!isset($data['donation_book'])){
            throw new ApiException('donation_book is not found',404);
        }

        if(!isset($data['donation_name'])){
            throw new ApiException('donation_name is not found',404);
        }

        if(!isset($data['donation_price'])){
            throw new ApiException('donation_price is not found',404);
        }

        if(!isset($data['donation_collect_id'])){
            throw new ApiException('donation_collect_id is not found',404);
        }else{
            if($data['donation_collect_id'] == ''){
                $data['donation_collect_id'] = 1;
            }
        }

        Db::startTrans();//开启事务
        try{
            //制作捐赠记录的数据
            $data = special_str($_POST);// 过滤特殊字符
            $data['donation_time']=time();//捐赠时间


            //捐书的奖励学币
            $coin = ceil($data['donation_price'] * 2);//书价的2倍向上取整
            if ($coin % 10 == 0) { //判定2倍向上取整后的书价能否对10取余，
                //能则将2倍向上取整后的书价赋给学币，不能则
                //先将10减去余数，余下的加上2倍向上取整后的书价
                //所获得的数为学币数
                $data['get_coin'] = $coin;
            } else {
                $coin = $coin + (10 - $coin % 10);
                $data['get_coin'] = $coin;
            }

            //查询会员信息
            $info = Db::name('user')->where(array('tel' => $data['donation_tel']))->find();
            if($info){ //判定是否为会员
                $user_id = $info['id'];
                $data['donation_id']=$info['id'];
                //1.根据基于user_id查询捐赠记录信息
                $history_donation= Db::name('donation')->where(array('donation_id'=>$user_id))->find();
                //2.判定是否有捐赠记录有捐书记录信息，则将当前的记录信息存入记录表当中
                if($history_donation){
                    $donation=new Donation($data);
                    $rec= $donation->allowField(true)->save();
                    if ($rec) {
                        Db::commit();//提交事务
                        return show(config('code.success'),'捐赠成功！');
                    } else {
                        return show(config('code.error'),'捐赠失败！');
                    }
                }else{ //没有捐赠记录

                    $donation=new Donation($data);
                    $rec= $donation->allowField(true)->save();
                    if($rec){
                        $coin_data['receive_id'] = $user_id;
                        $coin_data['month_coin']= 500 ;
                        $coins=new Coin($coin_data);
                        $d_rec = $coins->allowField(true)->save();
                        if($d_rec){
                            Db::commit();//提交事务
                            return show(config('code.success'),'首次捐赠成功,获得500奖励学币,请点击"领取本月学币按钮"领取！');
                        }else{
                            return show(config('code.error'),'coin表新增失败！');
                        }
                    }else {
                        return show(config('code.error'),'捐赠失败!');
                    }
                }
            }else{ //不是会员
                // 注册会员
                $user = array();
                $user['full_name']=$data['donation_name'];
                $user['tel']=$data['donation_tel'];
                $user['ctime']=$data['donation_time'];
                $user['user_auth']=3;
                $user['rec_id']= $data['donation_collect_id'];

                $users=new User($user);
                $res=$users->allowField(true)->save();//建立会员信息
                $user_id =  $users->id;
                if($res){
                    // 创建捐书记录
                    $data['donation_id']=$user_id;
                    $donation=new Donation($data);
                    $donation_res= $donation->allowField(true)->save();
                    if($donation_res){
                        // 建立学生账户
                        $student['student_id'] = $user_id;
                        $students=new StudentModel($student);
                        $stu_rec=$students->allowField(true)->save();
                        if($stu_rec){
                            // 建立coin表账户
                            $coin_data['receive_id'] = $user_id;
                            $coin_data['month_coin']= 500;
                            $coins=new Coin($coin_data);
                            $coin_rec = $coins->save();
                            if($coin_rec){
                                Db::commit();//提交事务
                                return show(config('code.success'),'首次捐赠成功,获得500奖励学币,请点击"领取本月学币按钮"领取！');
                            }else{
                                return show(config('code.error'),'coin表更新失败！');
                            }
                        }else {
                            return show(config('code.error'),'创建学生账户失败！');
                        }
                    }else{
                        return show(config('code.error'),'捐书失败！！');
                    }
                }else{
                    return show(config('code.error'),'注册会员失败！！');
                }
            }
        }catch (\Exception $e){
            Log::write($e->getMessage());
            Db::rollback();
            throw new ApiException($e->getMessage(),500);
        }

    }
}